package com.bblocks.redisqueue;

import cn.hutool.json.JSONUtil;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.Executor;

/**
 * 初始化队列监听
 */
@Component
//@ConditionalOnProperty(name = "spring.redis.redisson.enabled", matchIfMissing = true)
@ConditionalOnBean(name = "redissonConfig")
public class RedisDelayedQueueInit implements ApplicationContextAware {

    private static Logger logger = LoggerFactory.getLogger(RedisDelayedQueueInit.class);

    @Autowired
    RedissonClient redissonClient;
    @Qualifier("bblocksExecutor")
	@Autowired
	Executor executor;

    /**
     * 获取应用上下文并获取相应的接口实现类
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, RedisDelayedQueueListener> map = applicationContext.getBeansOfType(RedisDelayedQueueListener.class);
        for (Map.Entry<String, RedisDelayedQueueListener> taskEventListenerEntry : map.entrySet()) {
            String listenerName = taskEventListenerEntry.getValue().getClass().getName();
            startThread(RedisDelayedQueue.BB_DELAY_QUEUE_PRE+listenerName, taskEventListenerEntry.getValue());
        }
    }

    /**
     * 启动线程获取队列*
     *
     * @param queueName                 queueName
     * @param redisDelayedQueueListener 任务回调监听
     * @param <T>                       泛型
     * @return
     */
    private <T> void startThread(String queueName, RedisDelayedQueueListener<T> redisDelayedQueueListener) {
    	if(queueName.indexOf("$") != -1)
			queueName = queueName.substring(0,queueName.indexOf("$"));
		String finalQueueName = queueName;
        RBlockingQueue<T> blockingFairQueue = redissonClient.getBlockingQueue(finalQueueName);
        //由于此线程需要常驻，可以新建线程，不用交给线程池管理
		Thread thread = new Thread(() -> {
            logger.info("启动监听队列线程" + finalQueueName);
            while (true) {
                try {
                    T t = blockingFairQueue.take();
                    logger.info("监听队列线程{},获取到值:{}", finalQueueName, JSONUtil.toJsonStr(t));
                    /**
                    new Thread(() -> {
                        redisDelayedQueueListener.invoke(t);
                    }).start();
					 **/

					executor.execute(() -> {
						redisDelayedQueueListener.invoke(t);
					});

                } catch (Exception e) {
					logger.info("监听队列线程错误,", e);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException ex) {
					}
                }
            }
        });
        thread.setName(finalQueueName);
        thread.start();
    }

}
